# 使用方法：
#     方法1：将本文档入文件同目录，在“第10行”填上文件名，运行即可
#     方法2：本文档可以放在任何位置，要转换的文档使用绝对路径，用第12行替换前两行
#       原作者博客地址：https://blog.csdn.net/as604049322

import os
from PyPDF2 import PdfReader, PdfWriter

# 为文件名或路径填写方便，故把以下三行从main起始处提前到此处
relative_path = 'Gitee.pdf'
file = os.path.join(os.path.dirname(__file__), relative_path)
#file = r"D:\。。。\FileName.pdf" #文档绝对路径亦可用，替换上面代码+relative_path = 'Python单词汇总.pdf'

def get_pdf_Bookmark(filename):
    if isinstance(filename, str):
        pdf_reader = PdfReader(filename)
    else:
        pdf_reader = filename
    pagecount = len(pdf_reader.pages)
    # 用保存每个标题id所对应的页码
    idnum2pagenum = {}
    for i in range(pagecount):
        page = pdf_reader.pages[i]
        idnum2pagenum[page.indirect_ref.idnum] = i
    # 保存每个标题对应的标签数据，包括层级，标题和页码索引（页码-1）
    bookmark = []

    def get_pdf_Bookmark_inter(outlines, tab=0):
        for outline in outlines:
            if isinstance(outline, list):
                get_pdf_Bookmark_inter(outline, tab + 1)
            else:
                bookmark.append(
                    (tab, outline['/Title'], idnum2pagenum[outline.page.idnum]))

    get_pdf_Bookmark_inter(pdf_reader.outline)
    return bookmark


def pdf_write_bookmark(bookmark, pdf_file, compress=True):
    pdf_reader = PdfReader(pdf_file)
    num_pages = len(pdf_reader.pages)
    pdf_writer = PdfWriter()
    for page in pdf_reader.pages:
        if compress:
            page.compress_content_streams()
        pdf_writer.add_page(page)
    # pdf_reader.
    last_cache = [None] * (max(bookmark, key=lambda x: x[0])[0] + 1)
    for tab, title, pagenum in bookmark:
        if pagenum >= num_pages:
            continue
        parent = last_cache[tab - 1] if tab > 0 else None
        indirect_id = pdf_writer.add_outline_item(title, pagenum, parent=parent)
        last_cache[tab] = indirect_id
    pdf_writer.page_mode = "/UseOutlines"
    with open(pdf_file, "wb") as out:
        pdf_writer.write(out)
    print("已成功将书签添加到：", pdf_file)


if __name__ == '__main__':        
    bookmark = get_pdf_Bookmark(file)
    num_cache = [0] * 7
    last_tab = 0
    new_bookmark = []
    for tab, title, pagenum in bookmark:
        if tab > last_tab:
            num_cache[tab] = 1
        else:
            num_cache[tab] += 1
        new_title = title
        if not title[0].isdigit():
            new_title = ".".join(map(str, num_cache[:tab + 1])) + " " + title
        # print(tab, new_title, pagenum)
        new_bookmark.append((tab, new_title, pagenum))
        last_tab = tab
    pdf_write_bookmark(new_bookmark, file)
